<template>
  <el-container style="height: 100vh; padding: 20px;">
    <el-header>
      <h2>语音识别</h2>
    </el-header>
    <el-main>
      <el-row justify="center" align="middle">
        <el-col :span="12" class="text-center">
          <!-- 实时录音时长 -->
          <el-tooltip class="item" effect="dark" content="录音时长" placement="top">
            <el-tag type="info">{{ recordingTime }}秒</el-tag>
          </el-tooltip>
  
          <!-- 按钮组 -->
          <div class="button-group">
            <el-button v-if="!isRecording" type="primary" @click="startRecording" icon="el-icon-microphone">开始录音</el-button>
            <el-button v-if="isRecording" type="danger" @click="stopRecording" icon="el-icon-circle-close">停止录音</el-button>
            <el-button type="success" @click="transcribeAudio" :loading="loading">语音转文字</el-button>
            <!-- 新增上传按钮 -->
            <el-button type="warning" @click="$refs.fileInput.click()" icon="el-icon-upload">上传音频</el-button>
            <!-- 隐藏的文件输入 -->
            <input type="file" ref="fileInput" @change="handleAudioUpload" accept="audio/*" hidden>
          </div>
  
          <!-- 文件信息显示 -->
          <div v-if="audioData && audioData.name" class="file-info">
            已上传: {{ audioData.name }} ({{ formatFileSize(audioData.size) }})
          </div>
  
          <!-- 录音结果 -->
          <el-card v-if="transcription" class="result-card">
            <div class="result-title">识别结果：</div>
            <div>{{ transcription }}</div>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script>
import { ref } from 'vue';
import { ElButton, ElTag, ElTooltip, ElCard, ElRow, ElCol, ElContainer, ElHeader, ElMain } from 'element-plus';

export default {
  name: 'SpeechRecognition',
  components: {
    ElButton, ElTag, ElTooltip, ElCard, ElRow, ElCol, ElContainer, ElHeader, ElMain
  },
  setup() {
    const isRecording = ref(false);
    const recordingTime = ref(0);
    const transcription = ref('');
    const loading = ref(false);
    const audioData = ref(null);
    const fileInput = ref(null); // 文件输入引用

    let timer = null;
    let mediaRecorder = null;

    // 格式化文件大小
    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };

    // 处理音频上传
    const handleAudioUpload = (event) => {
      const file = event.target.files?.[0];
      if (file) {
        audioData.value = file;
        if (isRecording.value) stopRecording();
        recordingTime.value = 0;
      }
    };

    // 开始录音
    const startRecording = async () => {
      isRecording.value = true;
      recordingTime.value = 0;
      audioData.value = null;

      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      mediaRecorder = new MediaRecorder(stream);
      const chunks = [];

      mediaRecorder.ondataavailable = (event) => {
        chunks.push(event.data);
      };

      mediaRecorder.onstop = () => {
        const audioBlob = new Blob(chunks, { type: 'audio/pcm' });
        audioBlob.name = 'recording.pcm'; // 为录音文件命名
        audioData.value = audioBlob;
      };

      mediaRecorder.start();
      timer = setInterval(() => recordingTime.value++, 1000);
    };

    // 停止录音
    const stopRecording = () => {
      if (!isRecording.value || !mediaRecorder) return;
      isRecording.value = false;
      clearInterval(timer);
      mediaRecorder.stop();
    };

const transcribeAudio = async () => {
  if (!audioData.value) {
    transcription.value = '请选择音频文件或进行录音！';
    return;
  }

  loading.value = true;
  const formData = new FormData();

  const fileName = audioData.value.name || 'recording.pcm';
  formData.append('file', audioData.value, fileName);

  try {
    const response = await fetch('http://localhost:8080/listener', {
      method: 'POST',
      body: formData,
    });

    if (!response.ok) {
      throw new Error('网络请求失败');
    }

    const data = await response.json(); // 正确解析 JSON 响应

    if (data && data.msg) {
      // 仅提取 msg 字段内容
      transcription.value = data.msg.trim();
    } else {
      transcription.value = '语音识别失败，请重试！';
    }
  } catch (error) {
    console.error('语音识别失败:', error);
    transcription.value = '语音识别失败，请检查网络连接或重试！';
  } finally {
    loading.value = false;
  }
};

    return {
      isRecording,
      recordingTime,
      transcription,
      loading,
      audioData,
      fileInput,
      formatFileSize,
      startRecording,
      stopRecording,
      transcribeAudio,
      handleAudioUpload
    };
  }
};
</script>

<style scoped>
.text-center {
  text-align: center;
}
.button-group {
  margin-top: 20px;
}
.result-card {
  margin-top: 20px;
}
.result-title {
  font-weight: bold;
}
.file-info {
  margin-top: 10px;
  color: #666;
  font-size: 14px;
}
</style>